import math


class littleHeap:
    def __init__(self, data=None | list):
        if data == None:
            self.data = []
        else:
            self.data = data
            self.heapify()

    def heapify(self):
        size = len(self.data)
        if size in (0, 1):
            return

        for i in range(size // 2 - 1, -1, -1):
            self.heap_down_adjust(i, size)

    def heap_down_adjust(self, i, end):
        left = 2 * i + 1
        right = left + 1
        num = self.data
        while left < end:
            min_index = i
            if num[min_index] > num[left]:
                min_index = left
            if right < end and num[min_index] > num[right]:
                min_index = right
            if min_index == i:
                break
            num[i], num[min_index] = num[min_index], num[i]
            i = min_index
            left = 2 * i + 1
            right = left + 1

    def push(self, value):
        num = self.data
        num.append(value)
        index = len(num - 1)
        while index > 0:
            parent = (index - 1) // 2
            if num[parent] > num[index]:
                num[parent], num[index] = num[index], num[parent]
                index = parent
            else:
                break

    def pop(self):
        num = self.data
        if len(num) == 0:
            return None
        if len(num) == 1:
            return num.pop()
        value = num[0]
        num[0], num[-1] = num[-1], num[0]
        self.heap_down_adjust(0, len(num) - 1)

        return value

    def show(self):
        rank = int(math.log2(len(self.data))) + 1
        rank_num = 1
        index = 0
        nums = self.data
        for i in range(rank):
            black_str = " " * (2 * (rank - i))
            if i % 2 == 1:
                black_str = black_str + " "

            print(black_str, end="")
            print(nums[index : index + rank_num])
            index = index + rank_num
            rank_num = rank_num * 2
        print()


if __name__ == "__main__":
    heap = littleHeap([5, 1, 9, 4, 8, 3, 7, 2, 6])
    print(heap.data)
    heap.push(10)
    print(heap.data)
    print(heap.pop())
    print(heap.data)
    heap.show()
